/*
 * NamedNodeMapImpl.cpp
 *
 *  Created on: Apr 19, 2009
 *      Author: wrice
 */

#include "DOMCoreImp.h"
namespace DOMCoreImp {

NamedAttrMapImp::NamedAttrMapImp( ElementImp * parent )
: parentElementImp_( parent )
{
}

Attr * NamedAttrMapImp::getNamedItem(DOMString name) {
	NamedAttrsIterator iter = namedAttrs_.find(name);
	if( iter == namedAttrs_.end() ) return NULL;
	return iter->second;
}

Attr * NamedAttrMapImp::setNamedItem(Attr * newAttr) throw(DOMExceptionPtr) {
	if( NULL == newAttr ) return NULL;

	if( NULL != newAttr->getParentNode() )
		throw DOMExceptionPtr(new DOMExceptionImp(DOMException::INUSE_ATTRIBUTE_ERR));

	if( newAttr->getOwnerDocument() != getParentElementImp()->getOwnerDocument() )
		throw DOMExceptionPtr(new DOMExceptionImp(DOMException::WRONG_DOCUMENT_ERR));

	Attr * rst = NULL;
	NamedAttrsIterator iter = namedAttrs_.find( newAttr->getName() );
	const bool found = ( iter != namedAttrs_.end() );
	if( found ) {
		rst = iter->second;
		namedAttrs_.erase( newAttr->getName() );
	}

	namedAttrs_.insert( NamedAttrPair( newAttr->getName(), newAttr) );

	return rst;
}

Attr * NamedAttrMapImp::removeNamedItem(DOMString name) throw(DOMExceptionPtr) {
	NamedAttrsIterator iter = namedAttrs_.find(name);
	if( iter == namedAttrs_.end() )
		throw DOMExceptionPtr(new DOMExceptionImp(DOMException::NOT_FOUND_ERR));

	Attr * victim = iter->second;
	namedAttrs_.erase(name);
	return victim;
}

Attr * NamedAttrMapImp::item(unsigned long index) {
	NamedAttrsModifiableIterator iter = namedAttrs_.begin();
	for(unsigned long i = 0; i < index; ++i)
		++iter;
	return iter->second;
}

unsigned long NamedAttrMapImp::getLength() {
	return namedAttrs_.size();
}

ElementImp * NamedAttrMapImp::getParentElementImp() const {
	return parentElementImp_;
}

}
